from flask import Blueprint, jsonify, request
from src.models.user import User, db
import random
import string
from datetime import datetime

auth_bp = Blueprint('auth', __name__)

# 简化的验证码存储（生产环境应使用Redis等）
verification_codes = {}

def generate_verification_code():
    """生成6位数字验证码"""
    return ''.join(random.choices(string.digits, k=6))

@auth_bp.route('/send-code', methods=['POST'])
def send_verification_code():
    """发送验证码"""
    data = request.json
    phone = data.get('phone')
    
    if not phone:
        return jsonify({'error': '手机号不能为空'}), 400
    
    # 生成验证码
    code = generate_verification_code()
    verification_codes[phone] = {
        'code': code,
        'timestamp': datetime.utcnow()
    }
    
    # 在实际应用中，这里应该调用短信服务发送验证码
    # 为了演示，我们直接返回验证码
    return jsonify({
        'message': '验证码已发送',
        'code': code  # 仅用于演示，生产环境不应返回验证码
    })

@auth_bp.route('/login', methods=['POST'])
def login():
    """登录/注册"""
    data = request.json
    phone = data.get('phone')
    code = data.get('code')
    nickname = data.get('nickname', '')
    
    if not phone or not code:
        return jsonify({'error': '手机号和验证码不能为空'}), 400
    
    # 验证验证码
    stored_code_info = verification_codes.get(phone)
    if not stored_code_info or stored_code_info['code'] != code:
        return jsonify({'error': '验证码错误'}), 400
    
    # 检查验证码是否过期（5分钟）
    time_diff = datetime.utcnow() - stored_code_info['timestamp']
    if time_diff.total_seconds() > 300:  # 5分钟
        return jsonify({'error': '验证码已过期'}), 400
    
    # 查找或创建用户
    user = User.query.filter_by(phone=phone).first()
    if not user:
        # 首次登录，创建新用户
        if not nickname:
            nickname = f'用户{phone[-4:]}'  # 默认昵称
        
        user = User(phone=phone, nickname=nickname)
        db.session.add(user)
        db.session.commit()
    else:
        # 更新最后活跃时间
        user.last_active = datetime.utcnow()
        db.session.commit()
    
    # 清除已使用的验证码
    if phone in verification_codes:
        del verification_codes[phone]
    
    return jsonify({
        'message': '登录成功',
        'user': user.to_dict()
    })

@auth_bp.route('/profile/<int:user_id>', methods=['GET'])
def get_profile(user_id):
    """获取用户资料"""
    user = User.query.get_or_404(user_id)
    return jsonify(user.to_dict())

@auth_bp.route('/profile/<int:user_id>', methods=['PUT'])
def update_profile(user_id):
    """更新用户资料"""
    user = User.query.get_or_404(user_id)
    data = request.json
    
    if 'nickname' in data:
        user.nickname = data['nickname']
    if 'avatar_url' in data:
        user.avatar_url = data['avatar_url']
    
    user.last_active = datetime.utcnow()
    db.session.commit()
    
    return jsonify(user.to_dict())

